import { exec } from 'child_process';
import ejs from 'ejs';
import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';
import prompts from 'prompts';
import { rimrafSync } from 'rimraf';
import queryFiles from './queryFiles';

interface TypeConfig {
  projectName?: string;
  libName?: string;
  lang?: string;
}

const currentPath = process.env.PWD || '';
const read = (file: string) => fs.readFileSync(path.resolve(__dirname, file), 'utf-8');
let projectPath = '';
let config:TypeConfig = {};

(async () => {
  config = await prompts([
    {
      type: 'text',
      name: 'projectName',
      message: 'Project Name',
      initial: 'demo-wasm',
    },
    {
      type: 'text',
      name: 'libName',
      message: 'Wasm Library Name',
      initial: 'demo',
    },
    {
      type: 'select',
      name: 'lang',
      message: 'select one',
      choices: [
        {
          title: 'c++11',
          value: 'c++11',
        },
        {
          title: 'c++14',
          value: 'c++14',
        },
        {
          title: 'c++17',
          value: 'c++17',
        },
        {
          title: 'c++20',
          value: 'c++20',
        },
      ],
    },
  ]);
  projectPath = path.resolve(currentPath, config.projectName || '');
  const isPathExists = fs.existsSync(projectPath);

  if (isPathExists) {
    returnError(`[目录已存在]：${projectPath}`);
  }

  fs.mkdirSync(projectPath);
  console.log('项目目录已创建：', projectPath);
  cloneFiles();

})();

async function cloneFiles() {
  const now = Date.now();
  const shell = `git clone https://gitee.com/bproxy/create-cwasm.git ${now}`;

  exec(shell, (err, stdout, stderr) => {
    if (!err) {
      const tempPath = path.resolve(currentPath, now + '');
      copyFiles(tempPath);
    }
    if (err || stderr) {
      console.log(err || stderr.toString());
    }
  });
}

async function copyFiles(tempPath: string) {
  const template = path.resolve(tempPath, 'template');
  const sourceFiles = await queryFiles([`${template}/**`]);

  const placeDone = {};
  const newFiles: any = [];
  // copy files
  sourceFiles.map((file) => {
    console.log('parseFile', file);
    try {
      // 目标写入文件
      const dist = projectPath + file.replace(template, '');
      // 目标写入文件
      const dir = dist.replace(/\/[^/]+?$/, '');
      if (!placeDone[dir]) mkdirp.sync(dir);
      fs.copyFileSync(file, dist);
      newFiles.push(dist);
    } catch (err) {
      console.error('error', file);
    }
  });

  // parse files
  parseFiles(newFiles);

  rimrafSync(tempPath);
}

function returnError(message: string) {
  console.log(new Error(message));
  process.exit();
}

// render and rewrite
function parseFiles(sourceFiles: string[]) {
  sourceFiles.map((file) => {
    fs.writeFileSync(file, ejs.render(read(file), { config }));
    console.log('create file:', file);
  });
}
